package org.example;

public class Test3 {
    public int lastStoneWeightII(int[] stones) {
        int sum = 0,n = stones.length;
        for (int num : stones) sum += num;
        int[][] dp = new int[n+1][sum/2+1];
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= sum/2; j++) {
                dp[i][j] = dp[i-1][j];
                if (j >= stones[i-1]) {
                    dp[i][j] = Math.max(dp[i][j],dp[i-1][j-stones[i-1]] + stones[i-1]);
                }
            }
        }
        return Math.abs(sum-2*dp[n][sum/2]);
    }

    //优化
    public int lastStoneWeightII1(int[] stones) {
        int sum = 0,n = stones.length;
        for (int num : stones) sum += num;
        int[] dp = new int[sum/2+1];
        for (int i = 1; i <= n; i++) {
            for (int j = sum/2; j >= stones[i-1]; j--) {
                dp[j] = Math.max(dp[j],dp[j-stones[i-1]] + stones[i-1]);
            }
        }
        return Math.abs(sum-2*dp[sum/2]);
    }

    public static void main(String[] args) {
        Test3 test3 = new Test3();
        int[] arr = {2,7,4,1,8,1};
        test3.lastStoneWeightII(arr);
        System.out.println(4444);
    }
}
